document.addEventListener('DOMContentLoaded', () => {
    const imageContainer = document.getElementById('images');
    const selectAllBtn = document.getElementById('selectAll');
    const deselectAllBtn = document.getElementById('deselectAll');
    const downloadSelectedBtn = document.getElementById('downloadSelected');
    const applyFilterBtn = document.getElementById('applyFilter');
    const refreshImagesBtn = document.getElementById('refreshImages');
    const minWidthInput = document.getElementById('minWidth');
    const maxWidthInput = document.getElementById('maxWidth');
    const minHeightInput = document.getElementById('minHeight');
    const maxHeightInput = document.getElementById('maxHeight');

    let imagesData = [];
    let filteredImages = [];

    function fetchImages() {
        chrome.runtime.sendMessage({ type: 'getImages' }, (response) => {
            if (response && response.images) {
                imagesData = response.images;
                filteredImages = imagesData; // 初始化时不过滤
                displayImages(filteredImages);
            }
        });
    }
    function displayImages(images) {
        imageContainer.innerHTML = '';

        const buttons = [selectAllBtn, deselectAllBtn, downloadSelectedBtn];
        if (images.length === 0) {
            buttons.forEach(button => button.style.display = 'none');
            const message = document.createElement('div');
            message.innerText = "没有找到符合条件的图片。";
            message.style.color = '#333';
            message.style.textAlign = 'center';
            message.style.padding = '20px';
            imageContainer.appendChild(message);
            return;
        } else {
            buttons.forEach(button => button.style.display = 'inline-block');
        }

        images.forEach(image => {
            const imgElement = document.createElement('img');
            imgElement.src = image.src;
            imgElement.alt = image.alt;
            imgElement.style.width = '100%';

            const container = document.createElement('div');
            container.className = 'image-item';
            container.appendChild(imgElement);

            const resolution = document.createElement('div');
            resolution.className = 'resolution';
            resolution.innerText = `${image.width}x${image.height}`;
            container.appendChild(resolution);

            container.addEventListener('click', () => {
                container.classList.toggle('selected');
            });

            imageContainer.appendChild(container);
        });
    }

    function selectAllImages() {
        document.querySelectorAll('.image-item').forEach(item => item.classList.add('selected'));
    }

    function deselectAllImages() {
        document.querySelectorAll('.image-item').forEach(item => item.classList.remove('selected'));
    }

    function downloadSelectedImages() {
        const selectedImages = filteredImages.filter((image, index) => {
            const imageItem = document.querySelectorAll('.image-item')[index];
            return imageItem && imageItem.classList.contains('selected');
        });

        if (selectedImages.length === 0) {
            showAlertDialog("未选中图片");
            return;
        }

        selectedImages.forEach(image => {
            let baseFilename = image.alt ? image.alt.trim() : '';
            if (!baseFilename) {
                baseFilename = Date.now().toString();
            }
            const filename = baseFilename + '.png';

            chrome.downloads.download({
                url: image.src,
                filename: filename
            });
        });
    }

    function showAlertDialog(message) {
        const dialog = document.createElement('div');
        dialog.style.position = 'fixed';
        dialog.style.top = '50%';
        dialog.style.left = '50%';
        dialog.style.transform = 'translate(-50%, -50%)';
        dialog.style.background = 'rgba(0, 0, 0, 0.8)';
        dialog.style.color = 'white';
        dialog.style.padding = '20px';
        dialog.style.borderRadius = '5px';
        dialog.style.zIndex = '1000';
        dialog.innerText = message;

        document.body.appendChild(dialog);

        setTimeout(() => {
            document.body.removeChild(dialog);
        }, 1000);
    }


    function applyFilter() {
        const minWidth = parseInt(minWidthInput.value || 0);
        const maxWidth = parseInt(maxWidthInput.value || 99999);
        const minHeight = parseInt(minHeightInput.value || 0);
        const maxHeight = parseInt(maxHeightInput.value || 99999);

        filteredImages = imagesData.filter(image => {
            return image.width >= minWidth && image.width <= maxWidth &&
                image.height >= minHeight && image.height <= maxHeight;
        });

        displayImages(filteredImages);
    }

    refreshImagesBtn.addEventListener('click', fetchImages);
    selectAllBtn.addEventListener('click', selectAllImages);
    deselectAllBtn.addEventListener('click', deselectAllImages);
    downloadSelectedBtn.addEventListener('click', downloadSelectedImages);
    applyFilterBtn.addEventListener('click', applyFilter);

    fetchImages();
});
